package com.wpl.controller;

import com.wpl.bean.LoginBean;
import com.wpl.bean.User;
import com.wpl.common.WebResponse;
import com.wpl.service.ILoginService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/login/")
public class LoginController {

    @Resource
    private ILoginService loginService;

    /**
     * 验证账号
     *
     * @param username
     * @return
     */
    @GetMapping("/user")
    public WebResponse getUser(String username) {
        List<User> userList = loginService.getUser(username);
        if (!userList.isEmpty()) {
            return WebResponse.success(userList.get(0));
        } else {
            return WebResponse.failed();
        }

    }

    @GetMapping("/unauthorized")
    public WebResponse unauthorized(){
        return WebResponse.unauthorized("未登录");
    }

    /**
     * 登录校验
     *
     * @param loginBean
     * @param
     * @return
     */
    @PostMapping("/login")
    public WebResponse login(@RequestBody LoginBean loginBean){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(loginBean.getUsername(), loginBean.getPassword());
        try {
            subject.login(token);
            User user = loginService.getUser(loginBean.getUsername()).get(0);

            subject.getSession().setAttribute("user",user);
            return WebResponse.success(token);
        }catch (AuthenticationException e){
            e.printStackTrace();
            return WebResponse.failed("登录失败");
        }

    }

    /**
     * 注销登录
     *
     * @param
     * @return
     */
    @PostMapping("/loginout")
    public WebResponse loginout() {
        User user = new User(0);
        Session session = SecurityUtils.getSubject().getSession();
        String username = (String)session.getAttribute("username");
        user.setUsername(username);
        int count = loginService.changeOnline(user, username);
        if (count > 0) {
            session.stop();
            return WebResponse.success(count);
        } else {
            return WebResponse.failed();
        }

    }

}
